package com.wondertek.poms.core.service.impl;

import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.IBcInfoService;
import com.wondertek.poms.dao.po.BcInfo;
import com.wondertek.poms.dao.repo.IBcInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenjijiang
 * @description
 */
@Service
public class BcInfoServiceImpl extends ServiceImpl<BcInfo, Long> implements IBcInfoService {
	@Autowired
	private IBcInfoDao bcInfoDao;

	@Override
	public BcInfo deleteLogic(Long id) {
		return null;
	}

	@Override
	public BcInfo merge(BcInfo model) {
		return null;
	}

	@Override
	public BcInfo findByUserId(Long userId) {
		return bcInfoDao.findByUserId(userId);
	}

	@Override
	public List<BcInfo> findAllByGroups(String groups) {
		return bcInfoDao.findAllByGroups(groups);
	}

	@Override
	public Page<BcInfo> findAll(BcInfo bcInfo, int page, int rows, String sidx, String sord) {
		Specification<BcInfo> specification = getWhereClause(bcInfo);

		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);
		Pageable pageable = PageRequest.of(page - 1, rows, sort);

		return bcInfoDao.findAll(specification,pageable);
	}

	@Override
	public List<BcInfo> findAll(BcInfo bcInfo,String sidx,String sord){
		Specification<BcInfo> specification = getWhereClause(bcInfo);

		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);

		return bcInfoDao.findAll(specification,sort);
	}

	private Specification<BcInfo> getWhereClause(final BcInfo bcInfo) {
		return (Specification<BcInfo>) (r, q, cb) -> {
			List<Predicate> predicates = new ArrayList<>();
			//播控方ID：手工输入，支持精确查找；
			if (bcInfo.getBcId() != null) {
				predicates.add(cb.equal(r.get("bcId"),bcInfo.getBcId()));
			}
			//播控方名称：手工输入，支持模糊查询；
			if (bcInfo.getName() != null) {
				predicates.add(cb.like(r.get("name"), "%" + bcInfo.getName() + "%"));
			}
			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		};
	}
}
